(function ($) {
    //去除注释来查看编辑效
    //var periodData = [
    //    {
    //        "name": "网站导航", open: true, children: [
    //        {
    //            "name": "google", "url": "http://g.cn", "target": "_blank", open: true, children: [
    //            {
    //                "name": "google", "url": "http://g.cn", "target": "_blank", open: true, children: [
    //                {"name": "google", "url": "http://g.cn", "target": "_blank"},
    //                {"name": "baidu", "url": "http://baidu.com", "target": "_blank"},
    //                {"name": "sina", "url": "http://www.sina.com.cn", "target": "_blank"}
    //            ]
    //            },
    //            {"name": "baidu", "url": "http://baidu.com", "target": "_blank"},
    //            {"name": "sina", "url": "http://www.sina.com.cn", "target": "_blank"}
    //        ]
    //        },
    //        {"name": "baidu", "url": "http://baidu.com", "target": "_blank"},
    //        {"name": "sina", "url": "http://www.sina.com.cn", "target": "_blank"}
    //    ]
    //    },
    //    {
    //        "name": "网站导航", open: true
    //    }
    //];
    $.periodAction = function () {
        return {
            nodeName: '',		//编辑前 用来存储节点的名称 和编辑后数据对比，是否进行了修改
            zTreeObj: {},		//ztree实例化对象
            bookInfo: {},		//书本基本信息
            periodData: [],
            init: function () {
                this.listener();
                this.initLayui();
            },
            /**
             * 添加各按钮所需要的监听事件
             */
            listener: function () {
                $("#addLevel").click(function () {
                    $.periodAction.periodGetAll();
                    var name = "自定义目录_" + $.periodAction.uuid(5, 16);
                    treeNode = $.periodAction.zTreeObj.addNodes(null, {
                        isParent: true,
                        name: name
                    });
                    $.periodAction.addNode("0", name, Doman.url + Doman.addPeriod);
                });
            },
            uuid: function (len, radix) {
                var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
                var uuid = [], i;
                radix = radix || chars.length;

                if (len) {
                    // Compact form
                    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
                } else {
                    // rfc4122, version 4 form
                    var r;

                    // rfc4122 requires these characters
                    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                    uuid[14] = '4';

                    // Fill in random data.  At i==19 set the high bits of clock sequence as
                    // per rfc4122, sec. 4.1.5
                    for (i = 0; i < 36; i++) {
                        if (!uuid[i]) {
                            r = 0 | Math.random() * 16;
                            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                        }
                    }
                }

                return uuid.join('');
            },
            /**
             * 获取树节点
             */
            periodGetAll: function () {
                var periodGetAll = {};
                updateObject(Doman.url + Doman.periodGetAll, false, JSON.stringify(periodGetAll), function (result) {
                    if(result.code==200){
                        if (result.periodDTOList != null && result.periodDTOList != undefined && result.periodDTOList.length > 0) {
                            $.periodAction.initData(result.periodDTOList);
                        } else {
                            $.periodAction.periodData = [];
                            $.periodAction.initZtree($("#treeDemo"), $.periodAction.periodData);
                        }
                    }else if(result.code==400){
                        $.periodAction.periodData = [];
                        $.periodAction.initZtree($("#treeDemo"), $.periodAction.periodData);
                    }else{
                        layer.msg(result.message, {icon: 2});
                    }
                },function(){
                    layer.msg("网络不稳定，请重新刷新", {icon: 2});
                });
            },
            /**
             * 将树节点规范化
             */
            initData: function (data) {
                var periodData = [];
                $.each(data, function (i, period) {
                    var periodDataObj;
                    periodDataObj = {
                        name: period.periodName,
                        periodId: period.periodId,
                        fatherId: 0
                    };
                    if (period.subjectDTOList.length > 0) {
                        periodDataObj.open = true;
                        periodDataObj.children = [];
                        var subjectDataObj;
                        $.each(period.subjectDTOList, function (j, subjectData) {
                            subjectDataObj = {
                                name: subjectData.subjectName,
                                subjectId: subjectData.subjectId,
                                fatherId: period.periodId
                            };
                            if (period.subjectDTOList[j].editionDTOList.length > 0) {
                                subjectDataObj.open = true;
                                subjectDataObj.children = [];
                                var editionDataObj;
                                $.each(period.subjectDTOList[j].editionDTOList, function (k, editionData) {
                                    editionDataObj = {
                                        name: editionData.editionName,
                                        editionId: editionData.editionId,
                                        fatherId: period.subjectDTOList[j].subjectId
                                    };
                                    if (period.subjectDTOList[j].editionDTOList[k].belongDTOList.length > 0) {
                                        editionDataObj.open = true;
                                        editionDataObj.children = [];
                                        var belongDataObj;
                                        $.each(period.subjectDTOList[j].editionDTOList[k].belongDTOList, function (l, belongData) {
                                            belongDataObj = {
                                                name: belongData.belongName,
                                                belongId: belongData.belongId,
                                                fatherId: period.subjectDTOList[j].editionDTOList[k].editionId
                                            };
                                            editionDataObj.children.push(belongDataObj);
                                        });
                                    }
                                    subjectDataObj.children.push(editionDataObj);
                                });
                            }
                            periodDataObj.children.push(subjectDataObj);
                        });
                    }
                    periodData.push(periodDataObj);
                });
                $.periodAction.periodData = periodData;
                $.periodAction.initZtree($("#treeDemo"), periodData);
            },
            initZtree: function (othis, data) {
                var setting = {
                    view: {
                        addHoverDom: $.periodAction.addHoverDom,
                        removeHoverDom: $.periodAction.removeHoverDom,
                        showLine: false,
                        showIcon: false,
                        dblClickExpand: false,
                        fontCss: $.periodAction.setFontCss
                    },
                    edit: {
                        enable: true,
                        removeTitle: "删除节点",
                        renameTitle: "编辑节点名称",
                        showRemoveBtn: true,
                        editNameSelectAll: true
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pId",
                            rootPId: 0
                        }
                    },
                    callback: {
                        beforeEditName: $.periodAction.zTreeBeforeEditName,
                        onRename: $.periodAction.zTreeOnRename,
                        beforeRemove: $.periodAction.zTreeBeforeRemove
                    }
                };

//				zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
                var zNodes = data || [{
                        name: "自定义目录",
                        isParent: true
                    }];
                $.periodAction.zTreeObj = $.fn.zTree.init(othis, setting, zNodes);
            },
            setFontCss:function(treeId, treeNode){
                var obj={};
                if(treeNode.level == 0){
                    // obj={"font-size": "16px","font-weight": "bold"}
                }
                return obj;
            },
            addHoverDom: function (treeId, treeNode) {
                var sObj = $("#" + treeNode.tId + "_span");
                if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
                if ($("#addBtn_" + treeNode.tId).length > 0) return;
                var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                    + "' title='添加节点' onfocus='this.blur();'></span>";
                sObj.after(addStr);
                var btn = $("#addBtn_" + treeNode.tId);
                if (btn) btn.bind("click", function () {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    var childrenSize = 0;
                    if (treeNode.children != undefined) {
                        childrenSize = treeNode.children.length;
                    }
                    //var name = "自定义小节" + (++childrenSize);
                    var name = "自定义小节_" + $.periodAction.uuid(5, 16);
                    zTree.addNodes(treeNode, {
                        id: ("node" + $.periodAction.nodeCount),
                        name: name
                    });
                    var url = "";
                    var fatherId = "";
                    switch (treeNode.level) {
                        case 0:
                            url = Doman.url + Doman.addSubject;
                            fatherId = treeNode.periodId;
                            break;
                        case 1:
                            url = Doman.url + Doman.addEdition;
                            fatherId = treeNode.subjectId;
                            break;
                        case 2:
                            url = Doman.url + Doman.addBelong;
                            fatherId = treeNode.editionId;
                            break;
                        default:
                            url = "";
                            break;
                    }
                    $.periodAction.addNode(fatherId, name, url);
                    return false;
                });
            },
            removeHoverDom: function (treeId, treeNode) {
                $("#addBtn_" + treeNode.tId).unbind().remove();
            },
            /**
             * 添加学段、班级、年级等
             * **/
            addNode: function (fatherId, name, url) {
                var addNode = {
                    fatherId: fatherId,
                    name: name,
                    token: User.token
                };
                updateObject(url, true, JSON.stringify(addNode), function (result) {
                    if (result.code == 200) {
                        layer.msg(result.message, {icon: 1});
                    } else {
                        layer.msg(result.message, {icon: 2});
                    }
                    $.periodAction.periodGetAll();
                },function(){
                    layer.msg("网络不稳定，请重新刷新", {icon: 2});
                });
            },
            zTreeBeforeEditName: function (treeId, treeNode) {
                $.periodAction.nodeName = treeNode.name;
            },
            zTreeOnRename: function (event, treeId, treeNode, isCancel) {
                var treeNodeArr=treeNode.name.split("");
                if(treeNode.name==""){
                    layer.msg("name不能为空", {icon: 2});
                    $.periodAction.periodGetAll();
                }else if(treeNodeArr.length>20){
                    layer.msg("名称请勿超过20个字", {icon: 2});
                    $.periodAction.periodGetAll();
                }else{
                    if ($.periodAction.nodeName != treeNode.name) {
                        $.periodAction.editNode(event, treeId, treeNode, isCancel);
                    }
                }
            },
            zTreeBeforeRemove: function (treeId, treeNode) {
                var layer = (parent.layer === undefined ) ? layui.layer : parent.layer;
                layer.confirm('确认删除？', {
                    btn: ['确定', '取消'] //按钮
                }, function (index) {
                    $.periodAction.removeNode(treeId, treeNode);
                    layer.close(index);
                });
                return false;
            },
            /**
             * 请求数据库修改目录节点
             */
            editNode: function (event, treeId, treeNode, isCancel) {
                var layer = (parent.layer === undefined ) ? layui.layer : parent.layer;
                var index = layer.load(1, {
                    shade: [0.1, '#000'] //0.1透明度的白色背景
                });
                var url = "";
                var nodeId = "";
                switch (treeNode.level) {
                    case 0:
                        url = Doman.url + Doman.alterPeriod;
                        nodeId = treeNode.periodId;
                        break;
                    case 1:
                        url = Doman.url + Doman.alterSubject;
                        nodeId = treeNode.subjectId;
                        break;
                    case 2:
                        url = Doman.url + Doman.alterEdition;
                        nodeId = treeNode.editionId;
                        break;
                    case 3:
                        url = Doman.url + Doman.alterBelong;
                        nodeId = treeNode.belongId;
                        break;
                    default:
                        url = "";
                        break;
                }

                ///***提交添加或者修改目录数据数据 start ***/
                updateObject(url, true, JSON.stringify({
                    name: treeNode.name,
                    nodeId: nodeId,
                    token: User.token
                }), function (result) {
                    layer.close(index);
                    if (result.code == 200) {
                        layer.msg(result.message, {icon: 1});
                    } else {
                        layer.msg(result.message, {icon: 2});
                    }
                    $.periodAction.periodGetAll();
                },function(){
                    layer.msg("网络不稳定，请重新刷新", {icon: 2});
                });
                /***提交添加或者修改目录数据数据 end***/
            },
            /**
             * 请求数据库删除目录节点
             */
            removeNode: function (treeId, treeNode) {
                var layer = (parent.layer === undefined ) ? layui.layer : parent.layer;
                var index = layer.load(1, {
                    shade: [0.1, '#000'] //0.1透明度的白色背景
                });
                var url = "";
                var nodeId = "";
                switch (treeNode.level) {
                    case 0:
                        url = Doman.url + Doman.deletePeriod;
                        nodeId = treeNode.periodId;
                        break;
                    case 1:
                        url = Doman.url + Doman.deleteSubject;
                        nodeId = treeNode.subjectId;
                        break;
                    case 2:
                        url = Doman.url + Doman.deleteEdition;
                        nodeId = treeNode.editionId;
                        break;
                    case 3:
                        url = Doman.url + Doman.deleteBelong;
                        nodeId = treeNode.belongId;
                        break;
                    default:
                        url = "";
                        break;
                }
                /***删除目录 start ***/
                updateObject(url, true, JSON.stringify({
                    nodeId: nodeId,
                    token: User.token
                }), function (result) {
                    layer.close(index);
                    if (result.code == 200) {
                        layer.msg(result.message, {icon: 1});
                    } else {
                        layer.msg(result.message, {icon: 2});
                    }
                    $.periodAction.periodGetAll();
                },function(){
                    layer.msg("网络不稳定，请重新刷新", {icon: 2});
                });
                /***删除目录 end***/
            },
            initLayui: function () {
                layui.use(['layer', 'form'], function () { //独立版的layer无需执行这一句
                    var $ = layui.jquery, layer = layui.layer, form = layui.form; //独立版的layer无需执行这一句
                    var layer = (parent.layer === undefined ) ? layui.layer : parent.layer;
                    $.periodAction.periodGetAll();
                });
            }
        }
    }();
    $.periodAction.init();
})(jQuery);